package com.fd.framework.autoconfigure;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fd.framework.core.FdDateConverter;
import com.fd.framework.support.FdDateFormat;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.Date;

/**
 * web能力扩展增强
 * -对请求时间进行统一格式处理
 * 对GET请求参数中String时间类型统一转化为Date
 * 对POST请求body中, String时间类型统一转化为Date
 * -Long精度丢失问题处理
 * 关注:
 * org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration
 * org.springframework.boot.autoconfigure.http.JacksonHttpMessageConvertersConfiguration
 * ObjectMapper 将在处理特定类型时使用 SimpleModule 中注册的定制逻辑
 *
 * @author YangXiaoLong
 * @since 1.0.0
 */
public class WebStrengthAutoConfiguration {
    @Bean
    public Converter<String, Date> fdConverter() {
        return new FdDateConverter();
    }

    @Bean
    @Primary
    MappingJackson2HttpMessageConverter fdMappingJackson2HttpMessageConverter(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
        ObjectMapper objectMapper = jackson2ObjectMapperBuilder
                .serializerByType(Long.class, ToStringSerializer.instance)
                .serializerByType(Long.TYPE, ToStringSerializer.instance)
                .serializerByType(long.class, ToStringSerializer.instance)
                .build();
        objectMapper.setDateFormat(new FdDateFormat());
        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}
